import json
import random
class JFS:
    def __init__(self, path):
        self.path = path
        self.current = "/"
    def fsinit(self):
        with open(self.path, "w+") as f:
            init = {"initchunk": random.randint(1111111111111111, 9999999999999999),
                "data": {}
            }
            f.write(json.dumps(init))
    def dopen(self):
        with open(self.path, "r") as f:
            data = json.loads(f.read())
            self.filedata = data["data"]
    def dwrite(self, file, content):
        if not self.filedata[file]["belong"] == self.current:
            raise Exception("No such file or directory")
        if self.filedata[file]["type"] == 1:
            self.filedata[file]["content"] = content
        else:
            raise Exception("Is a directory")
    def dread(self, file):

        if not self.filedata[file]["belong"] == self.current:
            raise Exception("No such file or directory")
        if self.filedata[file]["type"] == 1:
            return self.filedata[file]["content"]
        else:
            raise Exception("Is a directory")
    def sync(self):
        data = {"initchunk": random.randint(1111111111111111, 9999999999999999),
                "data": self.filedata
            }
        with open(self.path, "w") as s:
            s.write(json.dumps(data))
    def dcreate(self, file):
        self.filedata[file] = {"type": 1,
                               "content": "",
                               "belong": self.current
                              }
    def mkdir(self, dir):
        self.filedata[dir] = {"type": 0,
                              "content": "",
                              "belong": self.current
                              }
    def chdir(self, dir):
        if dir in self.filedata:
            if self.filedata[dir]["type"] == 0:
                if self.filedata[dir]["belong"] == "/":
                    self.current = self.filedata[dir]["belong"] + dir
                else:
                    self.current = self.filedata[dir]["belong"] + "/" + dir
            else:
                raise Exception("Not a directory")
    def listall(self):
        return [i for i in self.filedata if self.filedata[i]["belong"] == self.current]
    def pwd(self):
        return self.current


